import Dep from './Dep';

const dep = new Dep();
/**
 console.log(dep);
 * Dep {
 *   effectMap: WeakMap{
 *     {a: 1, b: {…}} => {'a' => Set{ƒ, ƒ}, 'b' => Set(2)},
 *     {…} => Map(1),
 *     ...
 * }
 */

export default function reactive(data) {
  return new Proxy(data, {
    get(target, key) {
      const value = Reflect.get(target, key);

      //收集依赖
      dep.collect(target, key);

      return value !== null && typeof value === 'object'
        ? reactive(value)
        : value;
    },
    set(target, key, value) {
      const res = Reflect.set(target, key, value);

      //watch方法需要新老值
      const oldValue = target[key];

      //通知并执行所有回调函数
      dep.notify(target, key, value, oldValue);

      return res;
    }
  });
}
